<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 导入组件
import DashboardLayout from '../components/DashboardLayout.vue'
import EnergyGauge from '../components/EnergyGauge.vue'
import EnergyPie from '../components/EnergyPie.vue'
import ProductionStats from '../components/ProductionStats.vue'
import SalesTrend from '../components/SalesTrend.vue'
import DeviceRanking from '../components/DeviceRanking.vue'
import DeviceStatus from '../components/DeviceStatus.vue'

// 导入API
import { getDashboardData } from '@/api/dashboard'

// 添加加载状态标志
const loading = ref(true)

// 仪表盘数据
const dashboardData = ref({
  title: '智造云枢可视化总览',
  energy: {
    electricity: 0,
    water: 0,
    gas: 0
  },
  production: {
    total: 0,
    qualified: 0,
    defect: 0
  },
  sales: {
    year: 0,
    month: 0,
    day: 0
  },
  gasEmission: {
    year: 0,
    month: 0,
    day: 0
  },
  energyUsage: {
    total: 0,
    proportions: []
  },
  devices: [],
  salesTrend: {
    months: ['1月', '2月', '3月'],
    values: [0, 0, 0]
  }
})

// 数据刷新定时器
let timer = null

// 添加数据准备状态
const isDataReady = ref(false)

// 组件挂载时加载数据
onMounted(() => {
  loadData()
  
  // 每30秒刷新一次数据
  timer = setInterval(() => {
    loadData()
  }, 30000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 加载数据
const loadData = async () => {
  try {
    isDataReady.value = false // 加载开始前设置为false
    
    // const response = await getDashboardData()
    // if (response && response.code === 200) {
    //   // 确保数据正确映射
    //   const data = response.data
      
    //   // 如果后端返回了carbonEmission而不是gasEmission，做个兼容处理
    //   if (data.carbonEmission && !data.gasEmission) {
    //     data.gasEmission = data.carbonEmission
    //     delete data.carbonEmission
    //   }
      
    //   dashboardData.value = data
    // } else {
      useFallbackData()
    // }
    
    // 延迟设置ready状态，确保DOM有时间渲染
    setTimeout(() => {
      isDataReady.value = true
    }, 500)
  } catch (error) {
    console.error('加载数据失败:', error)
    useFallbackData()
    setTimeout(() => {
      isDataReady.value = true
    }, 500)
  }
}

// 备用数据，当接口请求失败时使用
const useFallbackData = () => {
  dashboardData.value = {
    title: '智造云枢可视化总览',
    energy: {
      electricity: 8000,
      water: 29640,
      gas: 56420
    },
    production: {
      total: 85600,
      qualified: 82400,
      defect: 3200
    },
    sales: {
      year: 1980000,
      month: 248000,
      day: 5600
    },
    gasEmission: {
      year: 56420,
      month: 5642,
      day: 169
    },
    energyUsage: {
      total: 94060,
      proportions: [
        { name: '生产线A', value: 47311, percentage: '50.3%', color: '#67C23A' },
        { name: '生产线B', value: 18812, percentage: '20.0%', color: '#E6A23C' },
        { name: '生产线C', value: 14109, percentage: '15.0%', color: '#409EFF' },
        { name: '其他', value: 13827, percentage: '14.7%', color: '#F56C6C' }
      ]
    },
    devices: [
      { id: 1, name: '冲压机A', status: '运行中', runtime: 1243, efficiency: '89%', power: 145 },
      { id: 2, name: '冲压机B', status: '运行中', runtime: 1532, efficiency: '92%', power: 153 },
      { id: 3, name: '数控机床A', status: '待机', runtime: 975, efficiency: '78%', power: 48 },
      { id: 4, name: '焊接机A', status: '运行中', runtime: 1689, efficiency: '95%', power: 187 },
      { id: 5, name: '焊接机B', status: '维护中', runtime: 0, efficiency: '0%', power: 0 },
      { id: 6, name: '装配线A', status: '运行中', runtime: 2140, efficiency: '91%', power: 174 },
      { id: 7, name: '装配线B', status: '运行中', runtime: 2032, efficiency: '88%', power: 168 }
    ],
    salesTrend: {
      months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      values: [720, 820, 960, 1030, 1180, 1230, 1350, 1420, 1560, 1740, 1850, 1980]
    }
  }
}
</script>

<template>
  <DashboardLayout :title="dashboardData.title" class="dashboard-container">
    <!-- 添加v-if确保数据加载后再渲染 -->
    <template v-if="isDataReady">
      <!-- 第一行 -->
      <el-row :gutter="20" >
        <!-- 能耗仪表盘 -->
        <el-col :span="8">
          <EnergyGauge :energyData="dashboardData.energy" />
        </el-col>
        
        <!-- 能源占比 -->
        <el-col :span="8">
          <EnergyPie :energyUsage="dashboardData.energyUsage" />
        </el-col>
        
        <!-- 生产统计 -->
        <el-col :span="8">
          <ProductionStats 
            :production="dashboardData.production" 
            :carbonEmission="dashboardData.gasEmission" 
          />
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row :gutter="20" class="middle-row" style=" ">
        <!-- 销售趋势 -->
        <el-col :span="12">
          <SalesTrend :salesTrend="dashboardData.salesTrend" />
        </el-col>
        
        <!-- 设备功率排名 -->
        <el-col :span="12">
          <DeviceRanking :devices="dashboardData.devices" />
        </el-col>
      </el-row>
      
      <!-- 第三行 -->
      <el-row :gutter="20" class="bottom-row device-status-container" style="margin-bottom: 30px; min-height: 400px;">
        <el-col :span="24" style="height: auto !important; min-height: 380px;">
          <DeviceStatus :devices="dashboardData.devices" />
        </el-col>
      </el-row>
    </template>
    <div v-else class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">数据加载中...</span>
    </div>
  </DashboardLayout>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #000c1a;
  color: #fff;
  overflow-y: auto; /* 启用垂直滚动 */

}
  .dashboard-container{
    background-image: url('../assets/images/bg.png');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

.dashboard {
  width: 100%;
  min-height: 100vh;
  padding: 10px;
  background-color: #000c1a;
  overflow-y: auto; /* 启用垂直滚动 */
}

.dashboard-header {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.dashboard-header h1 {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.dashboard-time {
  position: absolute;
  top: 0;
  right: 20px;
  color: #fff;
  font-size: 12px;
}

.dashboard-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow-y: auto; /* 启用垂直滚动 */
  padding-bottom: 20px; /* 底部留出空间 */
}

/* 自定义面板样式 */
.dashboard-panel {
  width: 100%;
  position: relative;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.panel-header {
  color: #29b6ff;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
  position: relative;
  padding-left: 15px;
  z-index: 10;
}

.panel-header::before,
.panel-header::after {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 12px;
  background-color: #29b6ff;
}

.panel-header::before {
  clip-path: polygon(0 0, 50% 20%, 50% 80%, 0 100%);
}

.panel-header::after {
  left: 4px;
  clip-path: polygon(0 20%, 100% 0, 100% 100%, 0 80%);
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 90%;
  position: relative;
  padding: 5px;
}

.energy-gauge {
  height: 85%;
}

/* 仪表盘标签样式 */
.gauge-labels {
  position: absolute;
  bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 5%;
}

.gauge-label-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 33.33%;
}

.gauge-label-item:first-child {
  align-items: center;
  transform: translateX(10%);
}

.gauge-label-item:nth-child(2) {
  align-items: center;
}

.gauge-label-item:last-child {
  align-items: center;
  transform: translateX(-10%);
}

.gauge-value {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 5px;
}

.gauge-name {
  font-size: 14px;
  color: #ccc;
}

.energy-pie {
  height: 95%;
}

.sales-chart,
.ranking-chart {
  height: 85%;
}

/* 数据总览样式 */
.data-overview {
  margin-bottom: 10px;
  height: 25%;
  padding: 0 5px;
}

.overview-section {
  margin-bottom: 10px;
}

.overview-title {
  font-size: 12px;
  color: #ccc;
  margin-bottom: 5px;
}

.overview-items {
  display: flex;
  justify-content: space-between;
}

.overview-item {
  flex: 1;
  text-align: center;
}

.item-label {
  font-size: 11px;
  color: #ccc;
  margin-bottom: 3px;
}

.item-value {
  font-size: 16px;
  font-weight: bold;
}

.item-value.success {
  color: #67c23a;
}

.item-value.info {
  color: #00ffff;
}

/* 表格样式 */
.data-table {
  height: 65%;
  overflow-y: auto;
  padding: 0 5px;
}

.el-table {
  background-color: transparent !important;
  --el-table-header-bg-color: rgba(10, 49, 97, 0.5) !important;
  --el-table-tr-bg-color: transparent !important;
  --el-table-border-color: #0a3161 !important;
  --el-table-text-color: #fff !important;
  --el-table-header-text-color: #29b6ff !important;
  --el-table-row-hover-bg-color: rgba(10, 49, 97, 0.3) !important;
}

.el-table--small {
  font-size: 11px;
}

.el-table th, .el-table td {
  padding: 4px 0;
}

.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: rgba(10, 49, 97, 0.3) !important;
}

.el-table .el-table__cell {
  background-color: transparent !important;
}

.el-table tr {
  background-color: transparent !important;
}

.el-table tr:nth-child(even) {
  background-color: rgba(0, 26, 51, 0.5) !important;
}

.el-empty {
  --el-empty-fill-color: rgba(255, 255, 255, 0.1);
  --el-empty-font-size: 12px;
  --el-empty-icon-size: 50px;
  color: #ccc;
  padding: 10px 0;
}

/* 调整第一行卡片高度 */
.dashboard-content .el-row:first-child .el-col {
  height: 320px;
  margin-bottom: 20px;
}

/* 调整第二行卡片高度 */
.dashboard-content .el-row:nth-child(2) .el-col {
  height: 300px;
  margin-bottom: 20px;
}

/* 调整第三行卡片高度 */
.dashboard-content .el-row:nth-child(3) .el-col {
  height: 300px;
}

/* 数据大屏边框调整 */
.dv-border-box-4, 
.dv-border-box-7, 
.dv-border-box-8, 
.dv-border-box-10,
.dv-border-box-11, 
.dv-border-box-12 {
  box-sizing: border-box;
  padding: 10px !important;
}

.dv-border-box-content {
  padding: 10px !important;
  position: relative;
  z-index: 1;
}

.el-col {
  padding: 0 10px !important;
}

/* 行间距调整 */
.middle-row {
  /* margin-bottom: 30px !important; */
  margin-top: 10x !important;
  /* padding-top: 15px; */
}

/* 第二行布局调整 */
.middle-row .el-col {
  margin-bottom: 30px;
}

/* 第三行布局调整 */
.bottom-row {
  margin-bottom: 30px !important;
}

/* 强制显示滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  display: block !important;
}

::-webkit-scrollbar-track {
  background: rgba(0, 26, 51, 0.5);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #3a7eff, #00eaff);
  border-radius: 4px;
  border: 2px solid rgba(0, 26, 51, 0.5);
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(to bottom, #599bff, #6df1ff);
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 70vh;
  color: #fff;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(0, 183, 255, 0.3);
  border-radius: 50%;
  border-top-color: #00b7ff;
  animation: spin 1s ease-in-out infinite;
}

.loading-text {
  margin-top: 20px;
  font-size: 18px;
  color: #00b7ff;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 调整整体布局控制高度 */
.dashboard-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow-y: auto; /* 启用垂直滚动 */
  padding-bottom: 20px; /* 底部留出空间 */
}

/* 确保容器有足够空间显示边框 */
.el-row {
  margin-left: 0 !important;
  margin-right: 0 !important;
  width: 100%;
}

/* 设置行和列的样式 */
.el-col {
  padding: 0 10px !important;
}

/* 设备状态容器样式 */
.device-status-container {
  height: auto !important;
  min-height: 350px !important;
  max-height: 450px !important;
  overflow-y: auto !important;
  padding: 0 5px;
  margin-bottom: 30px !important;
  scrollbar-width: thin;
  scrollbar-color: #3a7eff #001a33;
  display: block !important;
  width: 100% !important;
}

.device-status-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.device-status-container::-webkit-scrollbar-track {
  background: rgba(0, 26, 51, 0.5);
  border-radius: 4px;
}

.device-status-container::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #3a7eff, #00eaff);
  border-radius: 4px;
  border: 2px solid rgba(0, 26, 51, 0.5);
}

.device-status-container::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(to bottom, #599bff, #6df1ff);
}
</style>
